from django.apps import apps
from django.http import JsonResponse
from django.shortcuts import render
from rest_framework.decorators import action
from rest_framework.exceptions import APIException
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet

from mars.apps.orders.models import Order
from mars.apps.orders.serializers import OrderSerializer
from mars.apps.systems.models import FuncPrice
from mars.libs.wechat import WeChat as Wxpay
from mars.utils.common import get_order_code
from mars.utils.db import auto_commit

from .serializers import WxpaySerializer

# Create your views here.

VERSION_CODE = apps.get_app_config("oauth").__dict__["version_code"]

class WechatAPIView(ViewSet):
    """微信相关功能视图集"""

    @action(methods=["post"], detail=False, url_path="pay", url_name="pay")
    def pay_minigrog(self, request, *args, **kwargs):
        serializer = WxpaySerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        func_name = serializer.validated_data["func_name"]
        # 根据功能名称获取价格
        _func_price = FuncPrice.objects.first()
        # 获取功能名称
        func_verbose_name = FuncPrice._meta.get_field(func_name).verbose_name
        func_verbose_name = func_verbose_name.replace("价格", "")  # 删除字段名中出现的"price和价格"字符



        # 获取指定功能价格
        # auth_code = apps.get_app_config("oauth").auth_code

        price = _func_price.__getattribute__(func_name)
        if(VERSION_CODE == 0):
            price = 0.01
        elif(VERSION_CODE ==1):
            if(func_name == "human_style"):
                price = 0.01
                
        # 订单编号
        order_no = get_order_code()

        order_serializer = OrderSerializer(
            data={
                "order_no": order_no,
                "func_name": func_verbose_name,
                "price": price,
                "total": price,
                "user": request.user.id,
            }
        )
        order_serializer.is_valid(raise_exception=True)
        with auto_commit():
            order_serializer.save()

            prepay = Wxpay().pay_miniprog(
                order_no=order_serializer.validated_data["order_no"],
                openid=request.user.openid,
                func_name=func_verbose_name,
                amount=int(order_serializer.validated_data["price"] * 100),
            )

        return Response(prepay)


class WechatNotifyView(ViewSet):
    authentication_classes = []
    permission_classes = [AllowAny]

    @action(methods=["post"], detail=False, url_path="notify", url_name="notify")
    def pay_notify(self, request):
        # 定义支付成功后的订单处理函数
        def callback(resp):
            # 因业务简单不存在明细订单，所以采用的接收到支付成功回调后
            # 新增订单的方式，如果是复杂业务，应该采取的方式为：在生成
            # 预订单时，同时生成业务订单（待支付状态），接收到支付成功
            # 的回调时，修改订单状态
            order_no = resp.get("out_trade_no")

            # 创建订单
            try:
                order = Order.objects.get(order_no=order_no)
                if order.status == 0:
                    order.status = 1
                    order.save()
                return True
            except Order.DoesNotExist:
                return False

        return Wxpay().notify(request=request, callback=callback)
